package com.tiantianyuegou.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.CityListAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.City;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.sticky.StickyListHeadersListView;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import cz.msebera.android.httpclient.Header;

/**
 * 城市列表
 * Created by huyang on 2016/1/7 0007.
 */
public class CityListActivity extends BaseActivity implements View.OnClickListener {

    public static String CITYSELECT="cityListActivity";

    StickyListHeadersListView mListView;
    CityListAdapter mAdapter;
    String cname;
    List<City> allcommonCity = new ArrayList<City>();
    List<City> allCity = new ArrayList<City>();
    String TAG="CityListActivity";
    LoadingDialog loadingDialog;

    private final AsyncHttpClient mHttpClient = new AsyncHttpClient();
    LocationChangeListener mLocationListener = new LocationChangeListener();

    // 获取位置管理服务
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_citylist);
        Tools.changeSystemBar(this);
        setTitle("选择城市");
        initViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("CityListActivity", "start location");
        getLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("CityListActivity", "stop location");
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.removeUpdates(mLocationListener);
        }
    }

    @Override
    public void findViewByIds() {

        mListView = (StickyListHeadersListView) findViewById(R.id.list);
        mListView.setFastScrollEnabled(true);
        mListView.setFastScrollAlwaysVisible(true);
        mAdapter = new CityListAdapter(this);
//        TODO 需换成真实数据字段名称
        mListView.setAdapter(mAdapter);

    }

    @Override
    public void initListener() {
        loadingDialog=new LoadingDialog(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                TODO 徐换成真是字段名称
                cname = mAdapter.getItem(position).getCname();
                Constant.cName = cname;
                Intent intent = new Intent();
                intent.setAction("cityListActivity");
                intent.putExtra("cityName", cname);
                sendBroadcast(intent);
                finish();
            }
        });
    }

    @Override
    public void initData() {
        getallCity();
    }

    public void getallCity() {
        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        RequestParams params = new RequestParams();
        params.addBodyParameter("type", "4");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.SELECT_AREA, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_LONG).show();
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        allcommonCity.removeAll(allcommonCity);
                        if (code.equalsIgnoreCase("100")) ;
                        JSONArray jsonArray = jsonObject.getJSONArray("list");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject temp = jsonArray.getJSONObject(i);
                            int cid = temp.getInt("pid");
                            cname = temp.getString("pname");

                            String pfl = converterToFirstSpell(
                                    cname).toUpperCase().substring(
                                    0, 1);

                            City city = new City(cid, cname, pfl);
                            allcommonCity.add(city);
                        }
                        allCity.addAll(allcommonCity);

                        Collections.sort(allcommonCity,
                                new MyComparator()); // 排序
//                        TODO 徐换成真是字段名名称
                        mAdapter.addAll(allcommonCity);
                        mAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查网络设置");

            }
        });

    }

    @Override
    public void onClick(View view) {

    }

    /**
     * 汉字转换位汉语拼音首字母，英文字符不变
     *
     * @param chines 汉字
     * @return 拼音
     */
    public static String converterToFirstSpell(String chines) {
        String pinyinName = "";
        char[] nameChar = chines.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(
                            nameChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }

    public class MyComparator implements Comparator<City> {
        @Override
        public int compare(City c1, City c2) {
            if (c1.getPfl() == null || c2.getPfl() == null) {
                return -1;

            }
            return c1.getPfl().compareTo(c2.getPfl());
        }
    }

    private void getLocation() {
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) this.getSystemService(serviceName);
        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
        //GPS已经开启
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
                if (location != null) {
                    Log.e("TAG", location.getLatitude() + ":" + location.getLongitude());
                    getCityByGPSLocation(location.getLatitude(), location.getLongitude());
                    locationManager.removeUpdates(mLocationListener);
                } else {
                    //Toast.makeText(this, "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
                }
            }
        }
        // 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
        locationManager.requestLocationUpdates(provider, 3 * 1000, 500, mLocationListener);
    }

    private void getCityByGPSLocation(Double latitude, Double longitude) {
        String url = "http://api.map.baidu.com/geocoder?output=json&location="
                + latitude + "," + longitude + "&key=1WOjXfpIgo8rh4IqUl5VeYCb";
        mHttpClient.post(url, null, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("TAG","get city failure :"+s);
                Toast.makeText(CityListActivity.this, "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                try {
                    Log.e("TAG", "get city name:" + s);
                    JSONObject root = new JSONObject(s);
                    String status = root.getString("status");
                    if ("OK".equals(status)) {
                        JSONObject result = root.getJSONObject("result");
                        JSONObject addressComponent = result.getJSONObject("addressComponent");
                        String city = addressComponent.getString("city");
                        mAdapter.setLocationCity(city);
                        cname = city;
                    } else {
                        Toast.makeText(CityListActivity.this, "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class LocationChangeListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            //当位置发生改变的时候重新获取位置
            getCityByGPSLocation(location.getLatitude(), location.getLongitude());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    }
}
